package com.balance.anole.erp.security.login.service.impl;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.balance.anole.common.to.NavigateTO;

public class LocalMenuConfiguration {

	private String confXmlFilePath;

	private String rootName = "root";

	private Logger logger = Logger.getLogger(LocalMenuConfiguration.class);

	public LocalMenuConfiguration(String confXmlFilePath){
		this.confXmlFilePath = confXmlFilePath;
	}

	public String getConfXmlFilePath() {
		return confXmlFilePath;
	}

	public void setConfXmlFilePath(String confXmlFilePath) {
		this.confXmlFilePath = confXmlFilePath;
	}

	public String getRootName() {
		return rootName;
	}

	public void setRootName(String rootName) {
		this.rootName = rootName;
	}

	@SuppressWarnings("unchecked")
	public Set<NavigateTO> getMenus(){
		Set<NavigateTO> navigates = new HashSet<NavigateTO>();
		if(confXmlFilePath != null){
			SAXReader reader = new SAXReader();
			try {
				Document conf = reader.read(getClass().getClassLoader().getResourceAsStream(confXmlFilePath));
				List<Element> list = conf.selectNodes("//" + rootName + "/command");
				if(list != null && list.size() > 0){
					Iterator<Element> ite = list.iterator();
					while(ite.hasNext()){
						Element menu = ite.next();
						parseMenu(menu, navigates);
					}
				}
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


		return navigates;
	}

	private NavigateTO parseMenu(Element menu, Set<NavigateTO> set){
		if(NavigateTO.TYPE_EXPAND.equalsIgnoreCase(menu.attributeValue("type"))){
			//menu group
			NavigateTO group = new NavigateTO();
			group.setFunDesc(menu.attributeValue("fundesc"));
			group.setFunId(menu.attributeValue("funid"));
			group.setIconPath(menu.attributeValue("iconpath"));
			group.setType(menu.attributeValue("type"));
			group.setSn(Integer.parseInt(menu.attributeValue("sn")));
			Iterator ite= menu.selectNodes("command").iterator();
			while(ite.hasNext()){
				NavigateTO nt = parseMenu((Element) ite.next(), set);
				nt.setParentNavigate(group);
				logger.debug("Menu item after setting group : " + nt);
			}
			logger.debug("Parse menu group: " + group);
			set.add(group);
			return group;
		}else{
			//menu
			NavigateTO nt = new NavigateTO();
			nt.setCommand(menu.attributeValue("command"));
			nt.setFunDesc(menu.attributeValue("fundesc"));
			nt.setFunId(menu.attributeValue("funid"));
			nt.setIconPath(menu.attributeValue("iconpath"));
			nt.setType(menu.attributeValue("type"));
			nt.setSn(Integer.parseInt(menu.attributeValue("sn")));
			logger.debug("Parse menu item: " + nt);
			set.add(nt);
			return nt;
		}
	}
}
